﻿$(document).ready(function () {
 	
 	})

 	var indexF = 0;
 	//fileupload1_lblF_,fileupload1_rmlink,fileupload1_mdiv,fileupload1_hdnFileVal
 	function addlabel(v,fieldname) {
 		var m = $('<div class="iptdiv" id="lblF" ><img src="images/loading.gif" class="imgload" /><span>' + v + '</span><a href="#" name="'+ fieldname + '_rmlink">×</a>' +
			'<input type="hidden" name="'+ fieldname + '_hdnFileVal"/></div>')			
			.appendTo("#"+ fieldname +"_mdiv");

		//删除按钮
		m.find("a[name=" + fieldname + "_rmlink]").click(function () {
 			var _this = $(this);
 			$(_this.attr("ref")).remove(); //删除file input
 			_this.parent().remove();


 			var hdnobj = _this.parent().find("input:hidden");
 			//删除服务器临时文件
 			var u = "AjaxHandler.ashx?random=" + Math.random();
 			var v = { action: "delf", path: hdnobj.val() };

 			$.ajax({
 				type: "POST",
 				url: u,
 				data: v,
 				dataType: "json",
 				success: function (re) {
 					//for test, eventually it should do nothing here;
 					alert(re.msg);

 				},
 				error: function (r, e, re) {
 					//do nothing;
 					alert(e);
 				}
 			});

 		});
 	

 		return m[0];
 	}


	//选择文件后
 	function fileChange(e,fileid) {

		//TODO: 过滤文件类型

 		//添加Label控件
 		var showtxt = e.value.substring(e.value.lastIndexOf("\\") + 1);
 		var lblobj = addlabel(showtxt,fileid);
 		
 		alert(showtxt);

		window.setTimeout("doUpload('" + lblobj.id + "','" + fileid + "')",0); 

 	}



	//异步上传
 	function doUpload(lblobjID,fileid) {
 		
 		var fileobj = $("#" + fileid);
 		var op = $("#" + lblobjID);

 		//TODO:		验证导入文件

 		var loadingobj = op.find("img");
 		var hdnobj = op.find("input:hidden");

		//上传
 		var uploadre = $.ajaxFileUpload(
		{
			url: 'AjaxHandler.ashx?action=uploadf&random=' + Math.random(),
			secureuri: false,
			fileElementId: fileobj[0].id,
			dataType: 'json',
			success: function (data, status) {
				if (data.status == 'success') {

					hdnobj.val(data.msg);
					alert(data.msg);

					loadingobj.attr("src", "images/ok.png");
				}
				else {
					// unloading();
					alert(data.msg);
					loadingobj.attr("src", "images/cancel.png");
				}
			},
			error: function (data, status, e) {
				//unloading();
				alert(status + ": "+ e.message);
				loadingobj.attr("src", "images/cancel.png");
			}
		});


 		if (uploadre == false) {
 			loadingobj.hide();
 			loadingobj.attr("src", "images/cancel.png");

 		}
 	}